package com.pyb.common.datasource.aspectj;

import com.pyb.common.datasource.DynamicDataSource;
import com.pyb.common.datasource.anotations.Connection;
import com.pyb.common.datasource.enums.DataSourceEnum;
import com.pyb.common.exception.BizException;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * ConnectionAnotationAop
 *
 * @author chuchen.zhang
 * @date 17-2-27 下午4:01
 */
@Component
@Aspect
@Order(0)
public class ConnectionAnotationAop {

	private static final Logger logger = LoggerFactory.getLogger(ConnectionAnotationAop.class);

	/**
	 * 为标识了Connection注解的方法所在线程， 设置对应的数据源
	 */
	@Around("execution(* com.pyb..*(..))  && @annotation(connection)")
	public Object routeDataSource(ProceedingJoinPoint point, Connection connection) throws Throwable {
		DataSourceEnum dataSourceEnum = connection.datasource();
		if (dataSourceEnum == null) {
			throw new BizException("datasource in annotation is null");
		}
		try {
			DynamicDataSource.contextHolder.set(dataSourceEnum.getText());
			logger.debug("change datasource to {}", dataSourceEnum.getText());
			return point.proceed();
		} finally {
			DynamicDataSource.contextHolder.remove();
		}
	}
}
